package com.zx.zxpicture.domain.picture.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.zx.zxpicture.application.service.SpaceApplicationService;
import com.zx.zxpicture.application.service.UserApplicationService;
import com.zx.zxpicture.domain.picture.entity.Picture;
import com.zx.zxpicture.domain.picture.service.PictureDomainService;
import com.zx.zxpicture.domain.picture.valueobject.PictureReviewEnum;
import com.zx.zxpicture.domain.space.entity.Space;
import com.zx.zxpicture.domain.user.entity.User;
import com.zx.zxpicture.infrstructure.api.aliyunai.AliYunAiApi;
import com.zx.zxpicture.infrstructure.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.zx.zxpicture.infrstructure.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.zx.zxpicture.infrstructure.common.ErrorCode;
import com.zx.zxpicture.infrstructure.exception.BusinessException;
import com.zx.zxpicture.infrstructure.exception.ThrowUtils;
import com.zx.zxpicture.infrstructure.mapper.PictureMapper;
import com.zx.zxpicture.infrstructure.utils.ColorSimilarUtils;
import com.zx.zxpicture.infrstructure.utils.ExecutorPool;
import com.zx.zxpicture.infrstructure.utils.LockUtils;
import com.zx.zxpicture.infrstructure.utils.RegexUtils;
import com.zx.zxpicture.interfaces.dto.picture.CreatePictureOutPaintingTaskRequest;
import com.zx.zxpicture.interfaces.dto.picture.PictureEditByBatchRequest;
import com.zx.zxpicture.interfaces.dto.picture.PictureEditRequest;
import com.zx.zxpicture.interfaces.dto.picture.PictureQueryRequest;
import com.zx.zxpicture.interfaces.vo.PictureVO;
import com.zx.zxpicture.infrstructure.manager.CosManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.awt.*;
import java.util.List;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.zx.zxpicture.domain.picture.valueobject.PictureConstant.UPLOAD_URL_PRIVATE_REGEX;
import static com.zx.zxpicture.domain.picture.valueobject.PictureConstant.UPLOAD_URL_REGEX;

/**
* @author ZX
* @description 针对表【picture(图片)】的数据库操作Service实现
* @createDate 2025-02-19 15:03:21
*/
@Service
@Slf4j
public class PictureDomainApplicationServiceImpl extends ServiceImpl<PictureMapper, Picture>
    implements PictureDomainService {

    @Resource
    private SpaceApplicationService spaceApplicationService;
    @Resource
    private UserApplicationService userApplicationService;
    @Resource
    private CosManager cosManager;
    @Resource
    private AliYunAiApi aliYunAiApi;

    private final Cache<String, String> LOCAL_CACHE =
            Caffeine.newBuilder().initialCapacity(1024)
                    .maximumSize(10000L)
                    // 缓存 5 分钟移除
                    .expireAfterWrite(5L, TimeUnit.MINUTES)
                    .build();

    /**
     * 构造分页查询条件
     * @param pictureQueryRequest
     * @return
     */
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        //创建条件构造器
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        Date startTime = pictureQueryRequest.getStartTime();
        Date endTime = pictureQueryRequest.getEndTime();

        //开始构造条件
        // 从多字段中搜索
        //and( name LIKE '%???%' or introduction LIKE '%???%')
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        queryWrapper.ge(ObjUtil.isNotEmpty(startTime), "editTime", startTime);
        queryWrapper.lt(ObjUtil.isNotEmpty(endTime), "editTime", endTime);
        //构造查询空间的条件
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId),"spaceId",spaceId);
        queryWrapper.isNull(nullSpaceId,"spaceId");
        // JSON 数组查询
        // tags LIKE '%"tag1"%' AND tags LIKE '%"tag2"%'
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }
    /**
     * 填充图片审核参数
     * @param picture
     * @param loginUser
     */
    public void fillReviewParams(Picture picture,User loginUser){
        if(userApplicationService.isAdmin(loginUser)){
            picture.setReviewStatus(PictureReviewEnum.PASS.getValue());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewerId(loginUser.getId());
            picture.setReviewTime(new Date());
           return;
        }
        //如果是用户就是直接待审核
        picture.setReviewStatus(PictureReviewEnum.REVIEWING.getValue());
    }

    /**
     * 用户编辑图片
     * @param pictureEditRequest
     * @param loginUser
     */
    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
        //用户id作为锁，防止用户一瞬间点击多次，重复编辑
        if (!LockUtils.tryLock("pictureEdit"+ loginUser.getId())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "操作太频繁，请稍后再试");
        }
        if (pictureEditRequest == null || pictureEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        try {
            // 在此处将实体类和 DTO 进行转换
            Picture picture = new Picture();
            BeanUtils.copyProperties(pictureEditRequest, picture);
            // 注意将 list 转为 string
            picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
            // 设置编辑时间
            picture.setEditTime(new Date());
            // 数据校验
            validPicture(picture);
            // 判断是否存在
            long id = pictureEditRequest.getId();
            //拿到老图片
            Picture oldPicture = getById(id);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
            //改用saToken校验，校验权限
//            checkPictureAuth(loginUser, oldPicture);
            //补充审核内容
            fillReviewParams(picture,loginUser);
            // 操作数据库
            boolean result = updateById(picture);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        }finally {
            //释放锁
            LockUtils.unlock("pictureEdit"+ loginUser.getId());
        }
    }

    /**
     * 删除COS中的压缩图和缩略图
     * @param oldPicture 压缩图
     */
    @Override
    public void clearPictureFile(Picture oldPicture) {
        //todo 如果项目使用了秒传
        // 判断该图片是否被多条记录使用
        String pictureUrl = oldPicture.getUrl();
        long count = this.lambdaQuery()
                .eq(Picture::getUrl, pictureUrl)
                .count();
        // 有不止一条记录用到了该图片，不清理
        if (count > 1) {
            return;
        }
        //私人空间
        if(oldPicture.getSpaceId() != null){
            String urlKey = RegexUtils.findMatchingSubstrings(oldPicture.getUrl(), UPLOAD_URL_PRIVATE_REGEX, "");
            cosManager.deleteObject(urlKey);
            // 清理缩略图
            String thumbnailUrlKey = RegexUtils.findMatchingSubstrings(oldPicture.getThumbnailUrl(), UPLOAD_URL_PRIVATE_REGEX, "");
            if (StrUtil.isNotBlank(thumbnailUrlKey)) {
                cosManager.deleteObject(thumbnailUrlKey);
            }
            return;
        }
       //公共空间
        String urlKey = RegexUtils.findMatchingSubstrings(oldPicture.getUrl(), UPLOAD_URL_REGEX, "");
        cosManager.deleteObject(urlKey);
        // 清理缩略图
        String thumbnailUrlKey = RegexUtils.findMatchingSubstrings(oldPicture.getThumbnailUrl(), UPLOAD_URL_REGEX, "");
        if (StrUtil.isNotBlank(thumbnailUrlKey)) {
            cosManager.deleteObject(thumbnailUrlKey);
        }

    }


    /**
     * 根据颜色查询主色调相近的图片
     * @param spaceId 空间id
     * @param picColor 目标主色调 16进制
     * @param loginUser 用户
     * @return 图片列表（颜色越相近排名越靠前）
     */
    @Override
    public List<PictureVO> searchPictureVOByColor(Long spaceId, String picColor, User loginUser) {
        // 1. 校验参数
        ThrowUtils.throwIf(spaceId == null || StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2. 校验空间权限
        Space space = spaceApplicationService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }
        //3. 查询空间下的图片列表（必须有主色调）
        List<Picture> pictureList = lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();
        if(CollUtil.isEmpty(pictureList)){
            //返回空集合
            return Collections.emptyList();
        }
        Color targetColor = Color.decode(picColor); //目标颜色
        //遍历集合，根据主色调计算颜色差值，然后排序
        List<PictureVO> colorSimilarList = pictureList.stream()
                .filter(picture -> {
                    //获取图片主色调
                    String hexColor = picture.getPicColor(); //16进制
                    if (StrUtil.isBlank(hexColor)) {
                        //如果没有主色调，则过滤掉
                        return false;
                    }
                    Color color = Color.decode(hexColor);
                    double result = ColorSimilarUtils.calculateSimilarity(targetColor, color);
                    return result > 0.5;
                })
                //sorted是按照从小到大来排序的
                //根据计算出来的颜色差值来排序（颜色差值为double类型）
                .sorted(Comparator.comparingDouble(picture -> {
                    //获取图片主色调
                    String hexColor = picture.getPicColor(); //16进制
                    Color color = Color.decode(hexColor);
                    //问题：计算出来的结果是值越大，颜色越相近的，但是结果是反的，所以需要取反
                    return -ColorSimilarUtils.calculateSimilarity(targetColor, color);
                }))
                //Picture转换为PictureVO
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
        return colorSimilarList;
    }
    /**
     * 动态填充值
     * 格式：图片{序号}
     * {序号} 填充为 1 2 ...
     * @param pictureList 图片列表
     * @param nameRule 命名规则 {序号}
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if(StrUtil.isBlank(nameRule)){
            //不需要重命名
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                //使用正则替换命名规则中的所有{序号}
                picture.setName(nameRule.replaceAll("\\{序号}", String.valueOf(count++)));
            }
        }catch (Exception e){
            log.error("命名规则解析错误",e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"命名规则解析错误");
        }

    }


    /**
     * 线程池加并发批量编辑图片分类，标签和重命名（同时处理上万图片时可以使用）
     */
    @Transactional(rollbackFor = Exception.class)
    //有一个任务失败，所有数据回滚
    public void batchEditPictureMetadata(PictureEditByBatchRequest pictureEditByBatchRequest, Long spaceId, User loginUser) {
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();
        // 1. 校验参数
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        //2.校验空间权限
        if(spaceId == null){
            //批量操作公共图库，只有管理员有权限
            if(!userApplicationService.isAdmin(loginUser)){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }else {
            //私人空间，只有空间管理员有权限
            Space space = spaceApplicationService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            if (!loginUser.getId().equals(space.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
            }
        }

        // 查询空间下的图片
        List<Picture> pictureList = this.lambdaQuery()
                //指定查询字段
                .select(Picture::getId, Picture::getSpaceId)
                .eq(spaceId != null, Picture::getSpaceId, spaceId)
                .isNull(spaceId == null, Picture::getSpaceId)
                .in(Picture::getId, pictureIdList)
                .list();

        if (pictureList.isEmpty()) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "指定的图片不存在或不属于该空间");
        }

        // 获取全局线程池
        ThreadPoolExecutor executor = ExecutorPool.getInstance().getExecutor();

        // 分批处理避免长事务
        int batchSize = 100;
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        for (int i = 0; i < pictureList.size(); i += batchSize) {
            //每个线程操作的图片列表数据
            List<Picture> batch = pictureList.subList(i, Math.min(i + batchSize, pictureList.size()));

            // 异步处理每批数据
            //这个集合是记录这些每个任务的执行状态
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                batch.forEach(picture -> {
                    // 编辑分类和标签
                    if (pictureEditByBatchRequest.getCategory() != null) {
                        picture.setCategory(pictureEditByBatchRequest.getCategory());
                    }
                    if (pictureEditByBatchRequest.getTags() != null) {
                        picture.setTags(String.join(",", pictureEditByBatchRequest.getTags()));
                    }
                });
                //重命名
                String nameRule = pictureEditByBatchRequest.getNameRule();
                fillPictureWithNameRule(batch, nameRule);
                //插入数据库
                boolean result = this.updateBatchById(batch);
                if (!result) {
                    throw new BusinessException(ErrorCode.OPERATION_ERROR, "批量更新图片失败");
                }
                //将所有任务交给这个线程池执行
            }, executor);
            //将当前任务的执行结果状态添加到集合中
            futures.add(future);
        }

        // 等待所有任务完成
        //如果任务以异常结束，join() 会抛出 CompletionException，封装原始异常。
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
    }

    /**
     * 创建扩图任务
     * @param request 创建扩图任务请求参数
     * @return 创建扩图任务响应结果
     */
    public CreateOutPaintingTaskResponse createOutPaintingTask(CreatePictureOutPaintingTaskRequest request, User loginUser){
        //获取图片信息
        Long pictureId = request.getPictureId();
        //如果图片为空，那么抛出异常
        Picture picture = Optional.ofNullable(getById(pictureId))
                .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在"));
        //改用saToken校验，校验权限
//        checkPictureAuth(loginUser, picture);
        //构造扩图参数
        CreateOutPaintingTaskRequest createOutPaintingTaskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        CreateOutPaintingTaskRequest.Parameters parameters = request.getParameters();
        input.setImageUrl(picture.getUrl());
        createOutPaintingTaskRequest.setInput(input);
        createOutPaintingTaskRequest.setParameters(parameters);
        //创建任务
        return aliYunAiApi.createOutPaintingTask(createOutPaintingTaskRequest);
    }

    @Override
    public void validPicture(Picture picture) {
        picture.validPicture();
    }
}




